<template>
  <div class="writing_page">
    <div class="page_head">
      <div class="width-style">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-button type="text" style="font-size: 16px" @click="goHome">全民健康网</el-button>
          </el-col>
          <el-col :span="16">
            <div class="title_ipt_wrap">
              <span style="font-size: 14px">撰写文章：</span>
              <el-input
              placeholder="请输入标题（最多100字）"
              v-model="keywords"
              style="width: 600px"
              >
              </el-input>
            </div>
          </el-col>
          <el-col :span="4">
            <el-button type="text" @click="goPersonalCenter"
            >个人中心</el-button
            >
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="page_body">
      <div class="width-style card">
        <Toolbar
        style="border-bottom: 1px solid #ccc;"
        :editor="editor"
        :defaultConfig="toolbarConfig"
        :mode="mode"
        />
        <Editor
        style="height: 800px; overflow-y: hidden;text-align:left"
        v-model="contentEditor"
          :defaultConfig="editorConfig"
          :mode="mode"
          @onCreated="onCreated"
          />
      </div>
    </div>
    <div class="page_foo">
      <div class="width-style">
        <el-button type="primary" plain @click="UpdateDrafts">保存</el-button>
<!--        <el-button type="primary" plain @click="createDrafts">提交</el-button>-->
        <el-button type="primary" plain @click="submitDrafts">提交</el-button>
<!--        <el-button type="primary" plain @click="dialogVisible = true">提交</el-button>-->
      </div>
    </div>
    <el-dialog
      v-if="dialogVisible"
      title="发布设置"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
    >
      <el-form :model="subForm" label-width="90px">
        <!--        <el-form-item label="封面：">-->
        <!--          <el-radio-group v-model="subForm.cover">-->
        <!--            <el-radio label="single">单图</el-radio>-->
        <!--            <el-radio label="multiple">多图</el-radio>-->
        <!--          </el-radio-group>-->
        <!--        </el-form-item>-->
        <el-form-item label="上传封面：">
          <el-button
            class="el-upload el-upload--picture-card"
            @click="onImport()"
            v-show="showUpload && !proofImage"
          >
            <i class="el-icon-plus"></i>
          </el-button>
          <template v-if="proofImage">
            <el-image
              style="width: 100px; height: 100px"
              :src="proofImage"
              :preview-src-list="[proofImage]"
            >
            </el-image>
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              circle
              @click="proofImage = ''"
            ></el-button>
          </template>
          <el-upload
            v-show="!showUpload"
            ref="uploadFiles"
            :action="uploadFileUrl"
            :headers="{
              Authorization: authorization,
            }"
            accept=".jpg, .png"
            :limit="1"
            :show-file-list="false"
            :on-success="handlePictureCardSuccess"
            :on-remove="handleUploadRemove"
          >
          </el-upload>
        </el-form-item>
        <el-form-item label="文章分类：">
          <el-cascader
            ref="cascader"
            style="width: 230px"
            v-model="catalogueId"
            :options="classify"
            :props="{
              checkStrictly: true,
              emitPath: false,
              expandTrigger: 'hover',
              value: 'cataId',
              label: 'cataName',
            }"
          >
            <template slot-scope="{ node, data }">
              <div @click="handleChange(data)">
                <span v-if="data.cataId>=5">{{data.cataName}}</span>
<!--                <span>children{{data.children.length}}</span>-->
<!--                <span>node.isLeaf{{node.isLeaf}}</span>-->
<!--                <span v-if="!node.isLeaf && data.children.length">-->
<!--                  ({{ data.children.length }})-->
<!--                </span>-->
              </div>
            </template>
          </el-cascader>
        </el-form-item>
        <el-form-item label="作者：">
          <el-tag>{{ qmUserInfo.userName }}</el-tag>
        </el-form-item>
        <el-form-item label="文章类型：">
          <el-radio-group v-model="subForm.type">
            <el-radio label="0">原创</el-radio>
            <el-radio label="1">转载</el-radio>
            <!--            <el-radio label="modify">改写</el-radio>-->
          </el-radio-group>
        </el-form-item>
        <el-form-item label="附言：">
          <el-input
            style="width: 202px"
            v-model="subForm.note"
            placeholder="方便审核人员快速审核"
          ></el-input>
        </el-form-item>
        <el-form-item label="重要度：">
          <el-input
            type="number"
            style="width: 202px"
            v-model="subForm.importance"
            placeholder="请输入1-100"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="createArticle">发布</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title=""
      width="30%"
      :show-close="false"
      :close-on-click-modal="false"
      :visible.sync="subSuccessPop"
    >
      <el-result icon="success" title="发布成功">
        <template slot="extra">
          <el-button type="primary" size="medium" @click="subSuccessPop = false"
            >确定</el-button
          >
        </template>
      </el-result>
    </el-dialog>
  </div>
</template>

<script>
  import "@wangeditor/editor/dist/css/style.css";
  import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
  export default {
    name: "drafts",
    middleware: ['authenticated'],
    components: { Editor, Toolbar },
    data() {
      return {
        editor: null,
        toolbarConfig: {
          excludeKeys: [
            'uploadImage',//排除上传图片
            'uploadVideo',//排除上传视频
            // 排除菜单组，写菜单组 key 的值即可
          ]
        },
        editorConfig: {
          placeholder: "请输入内容...",
          MENU_CONF: {
            uploadImage: {
              // metaWithUrl: true,
              base64LimitSize: 10 * 1024 * 1024, // 10M 以下插入 base64
            },
          },
        },
        mode: "default",
        uploadFileUrl: "http://124.222.236.194:8080/ruoyi-admin/common/upload",
        authorization: "",
        contentEditor: "",
        options: {},
        toolBarwidth: "550px",
        keywords: "",
        dialogVisible: false,
        subSuccessPop: false,
        subForm: {
          artId: null,
          // cover: "single",
          category: "",
          type: "0",
          author: "",
          importance: "",
          note: "",
        },
        catalogueId: undefined,
        catalogueName: "",
        value: [],
        ArticleDetail: {},
        draftId:'',
        isAdd: true, //默认为新增
        proofImage: "",
        showUpload: true,
        qmUserInfo: {},
        upLoadId:null
      };
    },
    async asyncData({ app, store, route }) {
      if (route.query && route.query.draftId) {
        const res = await app.api.reqGetDrafts(route.query.draftId);
        return{
          ArticleDetail: res.data
        }
      }
    },

    mounted() {
     this.getUserInfo();
     this.authorization=this.$cookies.get(this.$api.TOKENKEY)
      this.getArtcatalogueList();
       this.draftId=this.ArticleDetail.draftId;
       this.contentEditor=this.ArticleDetail.context;
       this.keywords=this.ArticleDetail.title;
       this.upLoadId=this.ArticleDetail.upLoadId;
     // console.log(this.contentEditor);
    },
    beforeDestroy() {
      const editor = this.editor;
      if (editor == null) return;
      editor.destroy(); // 组件销毁时，及时销毁编辑器
    },
    methods: {
      onCreated(editor) {
        this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
      },
      async getUserInfo() {
        const res = await this.$api.reqUserInfo();
        this.qmUserInfo = res.user
      },
      async UpdateDrafts() {
        const res = await this.$api.reqUpdateDrafts({
          context: this.contentEditor,
          draftId: this.draftId,
          title: this.keywords,
          uploadId: this.qmUserInfo.userId, //用户ID全局获取之后替换
        })
        if(res.code===200){
          this.$message({
            type: "success",
            message: "保存成功",
          });
        }
      },
// 获取文章分类
      async getArtcatalogueList() {
        const res = await this.$api.reqArtsList();
        const deepArr = (arr) => {
          return arr.map((el) => {
            el.cataId = el.cataId + "";
            if (el.children && el.children.length) {
              deepArr(el.children);
            }
            return el;
          });
        };
        if (res.data) {
          this.classify = deepArr(res.data);
        }
      },
      // 上传文章封面
      onImport() {
        if (!this.proofImage) {
          this.$refs.uploadFiles.$refs["upload-inner"].handleClick();
        }
      },
      handleChange(nodeData) {
        this.catalogueId = nodeData.cataId;
        this.catalogueName = nodeData.cataName;
        this.$refs.cascader.checkedValue = nodeData.cataId;
        this.$refs.cascader.computePresentText();
        this.$refs.cascader.toggleDropDownVisible(false);
      },
      pubSubClick() {
        this.dialogVisible = false;
        this.subSuccessPop = true;
      },
      //通过getFile方法获取文件信息
      getFile(file, fileList) {
        console.log(file, "file");
      },
      // 预览和删除
      handleUploadRemove(file, fileList) {
        console.log(this.proofImage, "这个是base64的编码值");
        this.proofImage = "";
      },
      handlePictureCardSuccess(file) {
        console.log(file);
        this.proofImage = file.url;
        console.log(this.proofImage);
      },
          goHome() {
      let link = this.$router.resolve({
        path: "/home",
      });
      window.open(link.href, "_blank");
    },
    goPersonalCenter() {
      let link = this.$router.resolve({
        path: "/personalcenter",
      });
      window.open(link.href, "_blank");
    },
      submitDrafts(){
        // this.UpdateDrafts();
        this.dialogVisible = true;
        this.subSuccessPop = false;
      },
      async createDrafts() {
        const res = await this.$api.reqDrafts({
          context: this.contentEditor,
          draftId: this.draftId,
          title: this.keywords,
          uploadId: this.qmUserInfo.userId, //用户ID全局获取之后替换
        });
        if(res.code===200){
          this.$message({
            type: "success",
            message: "提交成功",
          });
        }
      },
      async submit(param) {
          const res = await this.$api.reqAddArticle(param);
          if (res.code === 200) {
            this.dialogVisible = false;
            this.subSuccessPop = true;
          }
      },
      createArticle() {
        if (!this.contentEditor || !this.keywords) {
          return;
        }
        const param = {
          artId: this.subForm.artId,
          artType: this.subForm.type,
          authorId: this.qmUserInfo.userId, //用户ID全局获取之后替换
          authorName: this.qmUserInfo.userName, //用户全局获取之后替换
          catalogueId: this.catalogueId - 0,
          catalogueName: this.catalogueName,
          content: this.contentEditor,
          // createBy: "string",
          // createTime: "2022-04-24T14:37:37.095Z",
          // deleteFlag: "string",
          favorites: 0,
          hits: 0,
          likes: 0,
          // params: {},
          // publishTime: new Date().toLocaleString().replaceAll("/", "-"),
          remark: this.subForm.note,
          // revieweFlag: "string",
          // searchValue: "string",
          thumbnail: this.proofImage,
          title: this.keywords,
          // updateBy: "string",
          // updateTime: "2022-04-24T14:37:37.095Z",
        };
        this.submit(param);
      },
    },
  };
</script>

<style lang="scss" scoped>
  .writing_page {
    width: 100%;
    background-color: #f6f7f9;
    text-align: left !important;
    padding-top: 62px;
    .page_head {
      width: 100%;
      background-color: #fff;
      padding: 10px 0;
      box-sizing: border-box;
      position: fixed;
      top: 0;
      left: 0;
      .title_ipt_wrap {
        display: flex;
        align-items: center;
      }
    }
    .page_body {
      .card {
        background-color: #fff;
        min-height: calc(100vh - 62px - 20px - 60px - 20px);
        margin-top: 20px;
        .ql-container {
          min-height: calc(100vh - 62px - 20px - 60px - 20px);
        }
        ::v-deep .ql-snow {
          border: 0 !important;
        }
      }
    }
    .page_foo {
      padding: 10px 0;
      width: 100%;
      background-color: #fff;
      margin-top: 20px;
      .width-style {
        text-align: right;
        padding-right: 100px;
        box-sizing: border-box;
      }
    }
  }

  //html * {
  //  outline: 1px solid red;
  //}
</style>
